package com.halixun.d2app;


import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.iot.iohub.TinyCommandManager;
import static com.halixun.d2app.BuildConfig.DEBUG;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.halixun.d2app.adapter.HomeNavigationAdapter;
import com.halixun.d2app.adapter.MyFootsAdapter;
import com.halixun.d2app.adapter.MyOrderListAdapter;
import com.halixun.d2app.base.BaseActivity;
import com.halixun.d2app.base.BaseResult;
import com.halixun.d2app.bean.FoodCategoryInfo;
import com.halixun.d2app.bean.OrderListInfo;
import com.halixun.d2app.bean.PayResultInfo;
import com.halixun.d2app.bean.requestbean.RequestOrderCodeParam;
import com.halixun.d2app.bean.requestbean.ScannerRequestInfo;
import com.halixun.d2app.dialog.ExitFragment;
import com.halixun.d2app.dialog.NumDialogFragment;
import com.halixun.d2app.dialog.PayStateDialogFragment;
import com.halixun.d2app.dialog.ScannerDialogFragment;
import com.halixun.d2app.net.CreateRequestEntity;
import com.halixun.d2app.net.DataState;
import com.halixun.d2app.net.errer.ResultVerifier;
import com.halixun.d2app.printer.PrinterUtils;
import com.halixun.d2app.printer.USBPrinter;
import com.halixun.d2app.ui.SettingActivity;
import com.halixun.d2app.utils.DataOperationUtil;
import com.halixun.d2app.utils.DensityUtil;
import com.halixun.d2app.utils.RequestDataUtils;
import com.halixun.d2app.utils.SystemUtil;
import com.halixun.d2app.utils.ToastUtils;
import com.halixun.d2app.utils.VersionUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;

public class MainActivity extends BaseActivity implements MyFootsAdapter.MyFootsAdapterListener
        , MyOrderListAdapter.MyOrderListAdapterListener,
        HomeNavigationAdapter.HomeNavigationListener {

    private RecyclerView footsRecyclerView, orderRecyclerView, navigationRecyclerView;
    private TextView centerClearOrder, centerNum, centerAdd, centerSub, centerDelete;
    private TextView totalPrice;
    private TextView btnXJPay;
    private TextView btnSMPay;
    private TextView btnCancelPay;
    private TextView headerTip;

    private List<OrderListInfo> orderList;
    private List<OrderListInfo> footsList;
    private List<FoodCategoryInfo> navigationList;

    private MyFootsAdapter footsAdapter;
    private MyOrderListAdapter orderAdapter;
    private HomeNavigationAdapter navigationAdapter;

    private int clickPosition = -1;
    private int navigationClickPosition = 0;
    private double priceNum;
    private String orderNumber;
    private String deviceId;

    private NumDialogFragment dialogFragment;
    private ScannerDialogFragment scannerDialogFragment;
    private ExitFragment exitFragment;

    private static final int REQUEST_LOCATION_PERMISSION = 0;
    private TinyCommandManager mCommandManager;
    private static final String TAG = "TinyCommandDemo";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkSelfPermission();

        mCommandManager = TinyCommandManager.getInstance(this);
        mCommandManager.bind();

        IntentFilter filter = new IntentFilter();
        filter.addAction(TinyCommandManager.ACTION_TINY_COMMAND_RECEIVER);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Handler handler = new Handler();
            registerReceiver(mReceiver, filter, TinyCommandManager.PERMISSION_TINY_COMMAND_RECEIVER, handler);
        } else {
            registerReceiver(mReceiver, filter);
        }

        hideActionBar();
        USBPrinter.initPrinter();
        initView();
        setAdapter();
        setListeners();
        getFoodTypes();
        initData();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        headerTip.setText(String.format(getString(R.string.version_tip), VersionUtil.getAppVersionName(this)));
    }

    @SuppressLint("NewApi")
    private void getFoodTypes() {
        CreateRequestEntity.getWebService().getFoodTypes(RequestDataUtils.getRequestDataParam(this)).enqueue(new Callback<BaseResult<List<FoodCategoryInfo>>>() {
            @Override
            public void onResponse(Call<BaseResult<List<FoodCategoryInfo>>> call, Response<BaseResult<List<FoodCategoryInfo>>> response) {
                if (ResultVerifier.isSucceed(response)) {
                    if (response.body().Data != null || response.body().Data.size() > 0) {
                        navigationList.clear();
                        FoodCategoryInfo info = new FoodCategoryInfo();
                        info.setSelected(true);
                        info.setClassName("全部");
                        info.setID(-1);
                        navigationList.add(info);
                        navigationList.addAll(response.body().Data);
                        navigationAdapter.notifyDataSetChanged();
                        getFootsData(navigationList.get(navigationClickPosition));
                    }
                } else {
                    ResultVerifier.serceErrers(response);
                }
            }

            @Override
            public void onFailure(Call<BaseResult<List<FoodCategoryInfo>>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
            }
        });
    }

    /**
     * 设置点击事件
     */
    private void setListeners() {
        footsRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                int index = parent.getChildAdapterPosition(view);
                int p = (index + 1) % 5;
                switch (p) {
                    case 1:
                        outRect.left = DensityUtil.dp2px(MainActivity.this, (float) 2.5);
                        outRect.right = DensityUtil.dp2px(MainActivity.this, (float) 0.5);
                        break;
                    case 2:
                        outRect.left = DensityUtil.dp2px(MainActivity.this, (float) 2);
                        outRect.right = DensityUtil.dp2px(MainActivity.this, (float) 1);
                        break;
                    case 3:
                        outRect.left = DensityUtil.dp2px(MainActivity.this, (float) 1.5);
                        outRect.right = DensityUtil.dp2px(MainActivity.this, (float) 1.5);
                        break;
                    case 4:
                        outRect.left = DensityUtil.dp2px(MainActivity.this, (float) 1);
                        outRect.right = DensityUtil.dp2px(MainActivity.this, (float) 2);
                        break;
                    case 0:
                        outRect.left = DensityUtil.dp2px(MainActivity.this, (float) 0.5);
                        outRect.right = DensityUtil.dp2px(MainActivity.this, (float) 2.5);
                        break;
                }
                if (index == 0 || index == 1 || index == 2 || index == 3 || index == 4) {
                    outRect.top = DensityUtil.dp2px(MainActivity.this, (float) 2.5);
                }
                outRect.bottom = DensityUtil.dp2px(MainActivity.this, (float) 2.5);
            }
        });
        navigationRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int index = parent.getChildLayoutPosition(view);
                if (index == 0) {
                    outRect.left = DensityUtil.dp2px(MainActivity.this, (float) 2.5);
                }
                outRect.right = DensityUtil.dp2px(MainActivity.this, (float) 2.5);
                outRect.top = DensityUtil.dp2px(MainActivity.this, (float) 1.5);
                outRect.bottom = DensityUtil.dp2px(MainActivity.this, (float) 1.5);
            }
        });
        centerNum.setOnClickListener(this);
        centerAdd.setOnClickListener(this);
        centerSub.setOnClickListener(this);
        centerDelete.setOnClickListener(this);
        btnXJPay.setOnClickListener(this);
        btnSMPay.setOnClickListener(this);
        btnCancelPay.setOnClickListener(this);
        centerClearOrder.setOnClickListener(this);
        findViewById(R.id.exit).setOnClickListener(this);
        footsAdapter.setMyFootsAdapterListener(this);
        orderAdapter.setMyOrderListAdapterListener(this);
        navigationAdapter.setOnHomeNavigationListener(this);
        findViewById(R.id.setting).setOnClickListener(this);
    }

    /**
     * 获取商品列表
     */
    @SuppressLint("NewApi")
    private void getFootsData(FoodCategoryInfo data) {
        showProgressDialog("数据获取中...");
        JsonObject object = new JsonObject();
        object.addProperty("classID", data.getID());
        object.addProperty("name", "");
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), object.toString());
        CreateRequestEntity.getWebService().getlists(body, RequestDataUtils.getRequestDataParam(this)).enqueue(new Callback<BaseResult<List<OrderListInfo>>>() {
            @Override
            public void onResponse(Call<BaseResult<List<OrderListInfo>>> call, Response<BaseResult<List<OrderListInfo>>> response) {
                dismissProgressDialog();
                if (ResultVerifier.isSucceed(response)) {
                    footsList.clear();
                    footsList.addAll(response.body().Data);
                    footsAdapter.notifyDataSetChanged();
                } else {
                    ResultVerifier.serceErrers(response);
                }
            }

            @Override
            public void onFailure(Call<BaseResult<List<OrderListInfo>>> call, Throwable t) {
                dismissProgressDialog();
                ResultVerifier.systerErrers(t);
            }
        });
    }

    /**
     * 设置adapter
     */
    private void setAdapter() {
        footsList = new ArrayList<>();
        orderList = new ArrayList<>();
        navigationList = new ArrayList<>();
        footsAdapter = new MyFootsAdapter(footsList);
        orderAdapter = new MyOrderListAdapter(orderList);
        navigationAdapter = new HomeNavigationAdapter(navigationList);
        navigationRecyclerView.setAdapter(navigationAdapter);
        footsRecyclerView.setAdapter(footsAdapter);
        orderRecyclerView.setAdapter(orderAdapter);
    }

    /**
     * 控件初始化
     */
    private void initView() {
        headerTip = findViewById(R.id.headerTip);

        footsRecyclerView = findViewById(R.id.footsRecyclerView);
        centerClearOrder = findViewById(R.id.centerClearOrder);
        orderRecyclerView = findViewById(R.id.orderRecyclerView);
        navigationRecyclerView = findViewById(R.id.navigationRecyclerView);

        centerNum = findViewById(R.id.centerNum);
        centerAdd = findViewById(R.id.centerAdd);
        centerSub = findViewById(R.id.centerSub);
        centerDelete = findViewById(R.id.centerDelete);

        totalPrice = findViewById(R.id.totalPrice);

        btnXJPay = findViewById(R.id.btnXJPay);
        btnSMPay = findViewById(R.id.btnSMPay);
        btnCancelPay = findViewById(R.id.btnCancelPay);
    }

    /**
     * 点击事件回调
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.centerNum:
                inputNum();
                break;
            case R.id.centerAdd:
                toAdd();
                break;
            case R.id.centerSub:
                toSub();
                break;
            case R.id.centerDelete:
                toDelete();
                break;
            case R.id.btnXJPay:
                toXJPay();
                break;
            case R.id.btnSMPay:
                toSMPay();
                break;
            case R.id.btnCancelPay:
                toCancelPay();
                break;
            case R.id.centerClearOrder:
                toClearOrder();
                break;
            case R.id.exit:
                loginOut();
                break;
            case R.id.setting:
                startActivity(new Intent(this, SettingActivity.class));
                break;
        }
    }

    /**
     * 退出登录
     */
    private void loginOut() {
        if (null == exitFragment) {
            exitFragment = new ExitFragment();
            exitFragment.setExitDialogListener(() -> {
                DataState.getInstance().appExitLogin();
                finish();
            });
        }
        exitFragment.show(getSupportFragmentManager(), "ExitFragment");
    }

    /**
     * 输入商品数目
     */
    private void inputNum() {
        if (orderList.size() > 0 && clickPosition != -1 && orderList.size() > clickPosition) {
            if (null == dialogFragment) {
                dialogFragment = new NumDialogFragment();
                dialogFragment.setNumDialogListener(number -> {
                    OrderListInfo info = orderList.get(clickPosition);
                    info.setCommodityNumber(Integer.valueOf(number));
                    orderAdapter.notifyItemChanged(clickPosition);
                    setTotalPrice();
                });
            }
            dialogFragment.show(getSupportFragmentManager(), "NumDialogFragment");
        } else ToastUtils.showBottomToast(R.string.home_select_foot);
    }

    /**
     * 现金支付
     */
    private void toXJPay() {
        if (null == orderList || orderList.size() == 0) {
            ToastUtils.showBottomToast(R.string.home_select_foot);
            return;
        }
        getOrderCode(null, 0);
    }

    /**
     * 扫码支付弹出接受框
     */
    private void toSMPay() {
        if (null == orderList || orderList.size() == 0) {
            ToastUtils.showBottomToast(R.string.home_select_foot);
            return;
        }

        for(Map.Entry<String, String> vo : RequestDataUtils.getRequestDataParam(this).entrySet()){
            vo.getKey();
            vo.getValue();
            if("DeviceId"==vo.getKey()){
                deviceId = vo.getValue();
            }
        }
        //下单支付
        this.createOrderCode();
    }

    /**
     * 取消支付
     */
    private void  toCancelPay(){
        ToastUtils.showBottomToast("取消");
        mCommandManager.sendCommand(TinyCommandManager.COMMAND_CANCEL, "");
    }

    /**
     * 下单
     */
    @SuppressLint({"CheckResult", "NewApi"})
    private void createOrderCode() {
        RequestOrderCodeParam param = new RequestOrderCodeParam();
        param.setTableId(0);
        param.setOrderId("");
        List<RequestOrderCodeParam.ItemsBean> list = new ArrayList<>();
        for (OrderListInfo info : orderList) {
            RequestOrderCodeParam.ItemsBean itemsBean = new RequestOrderCodeParam.ItemsBean();
            itemsBean.setClassID(info.getClassID());
            itemsBean.setClassName("");
            itemsBean.setProductID(info.getID());
            itemsBean.setProductName(info.getTitle());
            itemsBean.setOldPrice(info.getOldPrice());
            itemsBean.setPrice(info.getPrice());
            itemsBean.setProductCount(info.getCommodityNumber());
            itemsBean.setSumPrice(DataOperationUtil.mul(info.getCommodityNumber(), info.getPrice()));
            itemsBean.setUnit(info.getUnit());
            itemsBean.setIsNoDiscount(false);
            list.add(itemsBean);
        }
        param.setItems(list);
        showProgressDialog("支付中...");
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), new Gson().toJson(param));
        CreateRequestEntity.getWebService().getorder(body, RequestDataUtils.getRequestDataParam(this))
                .enqueue(new Callback<BaseResult<String>>() {
                    @Override
                    public void onResponse(Call<BaseResult<String>> call, Response<BaseResult<String>> response) {
                        if (ResultVerifier.isSucceed(response)) {
                            orderNumber = response.body().Data;
                            //刷脸支付
                            String temp = "{\"target\": \"ix\",\"content\": {\"deviceId\": "+deviceId+",\"bizNo\": "+orderNumber+",\"totalAmount\": "+priceNum+",\"from\": \"com.halixun.d2app\",\"method\": \"start\"}}";
                            //ToastUtils.showCenterToast(temp);
                            mCommandManager.sendCommand(TinyCommandManager.COMMAND_TINY_APP, temp);
                        } else {
                            dismissProgressDialog();
                            ResultVerifier.serceErrers(response);
                        }
                    }

                    @Override
                    public void onFailure(Call<BaseResult<String>> call, Throwable t) {
                        dismissProgressDialog();
                        ResultVerifier.systerErrers(t);
                    }
                });
    }

    /**
     * 获取订单
     *
     * @param number
     */
    @SuppressLint({"CheckResult", "NewApi"})
    private void getOrderCode(String number, int payType) {
        showProgressDialog(getString(R.string.home_paying));
        RequestOrderCodeParam param = new RequestOrderCodeParam();
        param.setTableId(0);
        param.setOrderId("");
        List<RequestOrderCodeParam.ItemsBean> list = new ArrayList<>();
        for (OrderListInfo info : orderList) {
            RequestOrderCodeParam.ItemsBean itemsBean = new RequestOrderCodeParam.ItemsBean();
            itemsBean.setClassID(info.getClassID());
            itemsBean.setClassName("");
            itemsBean.setProductID(info.getID());
            itemsBean.setProductName(info.getTitle());
            itemsBean.setOldPrice(info.getOldPrice());
            itemsBean.setPrice(info.getPrice());
            itemsBean.setProductCount(info.getCommodityNumber());
            itemsBean.setSumPrice(DataOperationUtil.mul(info.getCommodityNumber(), info.getPrice()));
            itemsBean.setUnit(info.getUnit());
            itemsBean.setIsNoDiscount(false);
            list.add(itemsBean);
        }
        param.setItems(list);
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), new Gson().toJson(param));
        CreateRequestEntity.getWebService().getorder(body, RequestDataUtils.getRequestDataParam(this))
                .enqueue(new Callback<BaseResult<String>>() {
                    @Override
                    public void onResponse(Call<BaseResult<String>> call, Response<BaseResult<String>> response) {
                        if (ResultVerifier.isSucceed(response)) {
                            if (payType == 0) {
                                toCashPay(response.body().Data);
                            } else {
                                toScannerPay(number, response.body().Data);
                            }
                        } else {
                            dismissProgressDialog();
//                            showPayState(false);
                            ResultVerifier.serceErrers(response);
                        }
                    }

                    @Override
                    public void onFailure(Call<BaseResult<String>> call, Throwable t) {
                        dismissProgressDialog();
                        ResultVerifier.systerErrers(t);
                    }
                });
    }

    /**
     * 现金支付
     *
     * @param data
     */
    @SuppressLint("NewApi")
    private void toCashPay(String data) {
        JsonObject object = new JsonObject();
        object.addProperty("orderId", data);
        object.addProperty("scanPayNo", priceNum);
        object.addProperty("posPayType", 1);
        object.addProperty("isClearTable", false);
        object.addProperty("discountPercent", 1);
        object.addProperty("payMoney", priceNum);
        object.addProperty("discountMoney", 0);
        object.addProperty("couponMoney", 0);
        object.addProperty("floorMoney", 0);
        object.addProperty("description", "欢迎再次光临！");
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), object.toString());
        CreateRequestEntity.getWebService().cashPay(body, RequestDataUtils.getRequestDataParam(this)).enqueue(new Callback<BaseResult<String>>() {
            @Override
            public void onResponse(Call<BaseResult<String>> call, Response<BaseResult<String>> response) {
                dismissProgressDialog();
                if (ResultVerifier.isSucceed(response)) {
                    PrinterUtils.print(orderList, data,7);
                    showPayState(true);
                } else {
                    showPayState(false);
                }
            }

            @Override
            public void onFailure(Call<BaseResult<String>> call, Throwable t) {
                dismissProgressDialog();
                showPayState(false);
            }
        });
    }

    /**
     * 付款码支付
     *
     * @param number
     * @param orderCode
     */
    @SuppressLint("NewApi")
    private void toScannerPay(String number, String orderCode) {
        ScannerRequestInfo info = new ScannerRequestInfo();
        info.setOrderId(orderCode);
        info.setDescription("欢迎再次光临！");
        info.setPayMoney(priceNum);
        info.setScanPayNo(number);
        info.setPosPayType(0);
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), new Gson().toJson(info));
        CreateRequestEntity.getWebService().scannerPay(body, RequestDataUtils.getRequestDataParam(this)).enqueue(new Callback<BaseResult<PayResultInfo>>() {
            @Override
            public void onResponse(Call<BaseResult<PayResultInfo>> call, Response<BaseResult<PayResultInfo>> response) {
                dismissProgressDialog();
                if (ResultVerifier.isSucceed(response)) {
                    if (response.body() != null && response.body().Data != null) {
                        if (response.body().Data.isPaySuccess()) {
                            PrinterUtils.print(orderList, orderCode,0);
                            showPayState(true);
                        } else {
                            ToastUtils.showCenterToast(R.string.home_pay_failed);
                        }
                    }
                } else {
                    showPayState(false);
                }
            }

            @Override
            public void onFailure(Call<BaseResult<PayResultInfo>> call, Throwable t) {
                dismissProgressDialog();
                showPayState(false);
            }
        });
    }


    /**
     * 展示扫码成功与失败提示
     *
     * @param payState
     */
    private void showPayState(boolean payState) {
        PayStateDialogFragment payStateDialogFragment = PayStateDialogFragment.getInstance(payState);
        payStateDialogFragment.show(getSupportFragmentManager(), "PayStateDialogFragment");
        if (payState) {
            toClearOrder();
        }
    }

    /**
     * 清单
     */
    private void toClearOrder() {
        if (null != orderList && orderList.size() > 0) {
            orderList.clear();
            orderAdapter.notifyDataSetChanged();
            clickPosition = -1;
            setTotalPrice();
        }
    }

    /**
     * 向指定商品上添加数目
     */
    private void toAdd() {
        if (orderList.size() > 0 && clickPosition != -1 && orderList.size() > clickPosition) {
            OrderListInfo info = orderList.get(clickPosition);
            int num = info.getCommodityNumber();
            info.setCommodityNumber(num += 1);
            orderAdapter.notifyItemChanged(clickPosition);
            setTotalPrice();
        } else ToastUtils.showBottomToast(R.string.home_select_foot);
    }

    /**
     * 从指定商品上减少数目
     */
    private void toSub() {
        if (orderList.size() > 0 && clickPosition != -1 && orderList.size() > clickPosition) {
            OrderListInfo info = orderList.get(clickPosition);
            int num = info.getCommodityNumber();
            if (num > 1) {
                info.setCommodityNumber(num -= 1);
                orderAdapter.notifyItemChanged(clickPosition);
                setTotalPrice();
            }
        } else ToastUtils.showBottomToast(R.string.home_select_foot);
    }

    /**
     * 删菜
     */
    private void toDelete() {
        if (orderList.size() > 0 && clickPosition != -1 && orderList.size() > clickPosition) {
            orderList.remove(clickPosition);
            orderAdapter.notifyItemRemoved(clickPosition);
            if (orderList.size() == 0) {
                clickPosition = -1;
            } else {
                clickPosition = orderList.size() - 1;
                orderList.get(clickPosition).setSelected(true);
                orderAdapter.notifyItemChanged(clickPosition, 0);
            }
            setTotalPrice();
        } else ToastUtils.showBottomToast(R.string.home_select_foot);
    }

    /**
     * 商品列表点击事件
     *
     * @param position
     */
    @Override
    public void onFootsClickListener(int position) {
        try {
            if (clickPosition != -1 && orderList.size() > clickPosition) {
                orderList.get(clickPosition).setSelected(false);
                orderAdapter.notifyItemChanged(clickPosition, 0);
            }
            OrderListInfo info = footsList.get(position).clone();
            info.setSelected(true);
            orderList.add(info);
            clickPosition = orderList.size() - 1;
            orderAdapter.notifyItemInserted(orderList.size() - 1);
            orderRecyclerView.smoothScrollToPosition(orderList.size() - 1);
            setTotalPrice();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 订单列表点击事件
     *
     * @param position
     */
    @Override
    public void onOrderListClickListener(int position) {
        if (clickPosition == position) {
            return;
        }
        if (clickPosition != -1) {
            orderList.get(clickPosition).setSelected(false);
            orderAdapter.notifyItemChanged(clickPosition, 0);
        }
        clickPosition = position;
        orderList.get(position).setSelected(true);
        orderAdapter.notifyItemChanged(position, 0);
    }

    /**
     * 设置合计
     */
    private void setTotalPrice() {
        double tPrice = 0;
        for (OrderListInfo info : orderList) {
            tPrice = DataOperationUtil.add(tPrice, DataOperationUtil.mul(info.getPrice()
                    , info.getCommodityNumber()));
        }
        priceNum = tPrice;
        totalPrice.setText("合计:￥" + tPrice);
    }

    @Override
    public void onHomeNavigationListener(int position) {
        if (position == navigationClickPosition) return;
        navigationList.get(position).setSelected(true);
        navigationAdapter.notifyItemChanged(position);
        if (navigationClickPosition >= 0 && navigationClickPosition < navigationList.size()) {
            navigationList.get(navigationClickPosition).setSelected(false);
            navigationAdapter.notifyItemChanged(navigationClickPosition);
            navigationClickPosition = position;
            getFootsData(navigationList.get(navigationClickPosition));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCommandManager.unbind();
        unregisterReceiver(mReceiver);
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive: " + intent.getAction());
            final String target = intent.getStringExtra(TinyCommandManager.EXTRA_TINY_COMMAND_TARGET);
            final String content = intent.getStringExtra(TinyCommandManager.EXTRA_TINY_COMMAND_CONTENT);
            final String temp = target + "-->" + content;
            showPayState(true);
            dismissProgressDialog();
            if (headerTip != null) {
                //headerTip.setText("接收指令：" + temp);
            }
        }
    };

    private void checkSelfPermission() {
        ArrayList<String> permissions = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION)!= PERMISSION_GRANTED) {
            permissions.add(ACCESS_COARSE_LOCATION);
        }
        if (ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) != PERMISSION_GRANTED) {
            permissions.add(ACCESS_FINE_LOCATION);
        }
        if (permissions.size() > 0) {
            ActivityCompat.requestPermissions(this, permissions.toArray(new String[0]),
                    REQUEST_LOCATION_PERMISSION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_LOCATION_PERMISSION:
                int result = 0;
                for (int i = 0; i < permissions.length; ++i) {
                    if (ACCESS_FINE_LOCATION.equals(permissions[i]) ||
                            ACCESS_COARSE_LOCATION.equals(permissions[i])) {
                        if (grantResults[i] == PERMISSION_GRANTED) {
                            result++;
                        }
                    }
                }
                if (result == 2) {
                    if (DEBUG) Toast.makeText(this,
                            "Location permissions granted", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(this,
                            "Not granted location permissions", Toast.LENGTH_LONG).show();
                    finish();
                }
        }
    }

}
